package com.dog.modules.iot.mqtt.codec;

import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


/**
 * 用于保存或者获取加密的secretKey和IV服务
 */
@Service
@Slf4j
public class SecretService {

    private static final String SECRET_KEY_PREFIX = "RCPD";
    private static final String IV = "ROBOT_COMMANDKEY";
    private static final int deviceCode_size = 12;


    /**
     * 保存设备通信消息加密密钥
     *
     * @param key
     */
    public void saveSecretKey(SecretKey key) {
        //do nothing
    }

    public SecretKey getSecretKey(String deviceCode) {
        if (StringUtils.isBlank(deviceCode)) {
            log.error("getSecreKey with null deviceCode");
            return null;
        }
        SecretKey key = new SecretKey();
        key.setDeviceCode(deviceCode);
//        if (deviceCode.length() > deviceCode_size) {
//            //大于12位取12位子字符串
//            deviceCode = deviceCode.substring(0, deviceCode_size);
//        } else if (deviceCode.length() < deviceCode_size) {
//            //小于12位用0补齐
//            int temp = deviceCode_size - deviceCode.length();
//            while (temp > 0) {
//                deviceCode = deviceCode + "0";
//                temp--;
//            }
//        }
        key.setSecretKey(SECRET_KEY_PREFIX + deviceCode);
        key.setIv(IV);
        return key;
    }
}
